var URL = "http://178640.ichengyun.net/";
var apiURL = "http://123.1.189.113" + '/api/';
var imgurl = URL;
var HTML_W = 'widget://html/';
var _appsecret = '6b9528016630c063ad9c75b53708356c';

function islogin() {
    if (!$api.getStorage('token')) {
        alert("common token获取失败")
        openWin('login');
    }
};

function getToken() {
    if ($api.getStorage('token')) {
        return $api.getStorage('token');
    } else {
        return 'token';
    }
}

function usercopy(text) {
    //text为需要复制的文本
    var clipBoard = api.require('clipBoard');
    clipBoard.set({
        value: text
    }, function(ret, err) {
        if (ret) {
            console.log('復製成功');
        } else {
            console.log('複製失敗，請重試');
        }
    });
}

function openFrame(url, name) {
    // 解析属性	消除点击300S 延时问题 tapmode
    api.parseTapmode();
    api.openFrame({
        name: name,
        url: 'widget://html/' + url + '.html',
        bounces: false,
        allowEdit: true,
        reload: true,
        rect: {
            x: 0,
            y: 0,
            w: 'auto',
            h: 'auto'
        },
    })
}

function out() {
    $api.setStorage('token', null);
    $api.setStorage('user', null);
}
//页面跳转
function openWin(url, param, slidBackEnabled) {
    var color = document.querySelector('#header').getAttribute("data-color");
    var param = param || {};
    if (slidBackEnabled == null)
        slidBackEnabled = true;
    param.heardColor = color;
    api.openWin({
        name: url,
        url: HTML_W + url + ".html",
        pageParam: param,
        slidBackEnabled: slidBackEnabled,
        allowEdit: true,
        reload: true
    });
};

function _ajax(url, data, callback) {
    data = data || {};
    data['token'] = getToken();
    var timestamp = Date.parse(new Date());
    var sign = getSign(data, timestamp);
    data['sign'] = sign;
    data['time'] = timestamp;
    // console.log(apiURL + url);
    console.log('发送参数'+JSON.stringify(data));
    var postdata = {
        body: data
    };
    // console.log(JSON.stringify(postdata))
    api.ajax({
        url: apiURL + url,
        method: 'POST',
        headers: {
            'Content-Type': 'application/json;charset=utf-8'
        },
        data: postdata
    }, callback);
};
// 生成sign签名
function getSign(params, timestamp) {
    var relurt = '';
    if (typeof params == "string") {
        relurt = paramsStrSort(params, timestamp);
    } else if (typeof params == "object") {
        // console.log('原始加密数组' + JSON.stringify(params));
        var relurt = jsonSort(params);
        relurt = paramsStrSort(relurt, timestamp);
    }
    return relurt;
}
// getSign用到的字符串处理
function paramsStrSort(paramsStr, timestamp) {
    var newUrl = paramsStr + '@' + timestamp + '@' + _appsecret;
    // console.log('加密前字符串' + newUrl);
    return md5(newUrl);
}

function jsonSort(jsonObj) {
    let arr = [];
    for (var key in jsonObj) {
        if (jsonObj[key] != undefined)
            arr.push(key);
        // console.log('键值对-' + key + '-' + jsonObj[key]);
    }
    arr.sort();
    let str = '';
    for (var i in arr) {
        str += jsonObj[arr[i]] + "&"
    }
    var relurt = str.substr(0, str.length - 1);
    return relurt;
}
// msg提示
function _msg(title, duration, location) {
    //top            //顶部
    //middle        //中间
    //bottom        //底部
    if (!location) {
        location = 'middle';
    }
    if (!duration) {
        duration = 2000;
    }
    api.toast({
        msg: title,
        duration: duration,
        location: location
    });
}

// 加载提示
//var layerload;
// 关闭 提示
function _loadingCloes() {
    //layer.close(layerload);
    api.hideProgress();
    api.refreshHeaderLoadDone();
    var activity = api.require('UILoading');
    activity.closeKeyFrame();
};

//loading层
function _loading(title, text) {
    var activity = api.require('UILoading');
    activity.keyFrame({
        rect: {
            w: 132.5,
            h: 145
        },
        styles: {
            bg: 'rgba(0,0,0,0.5)',
            corner: 8,
            interval: 50,
            frame: {
                w: 75,
                h: 90
            }
        },
        //字符串类型；加载状态动画的关键帧图片路径；
        content: [{
            frame: 'widget://image/xiala/dropdown_anim_00.png'
        }, {
            frame: 'widget://image/xiala/dropdown_anim_01.png'
        }, {
            frame: 'widget://image/xiala/dropdown_anim_02.png'
        }, {
            frame: 'widget://image/xiala/dropdown_anim_03.png'
        }, {
            frame: 'widget://image/xiala/dropdown_anim_04.png'
        }, {
            frame: 'widget://image/xiala/dropdown_anim_05.png'
        }, {
            frame: 'widget://image/xiala/dropdown_anim_06.png'
        }, {
            frame: 'widget://image/xiala/dropdown_anim_07.png'
        }, {
            frame: 'widget://image/xiala/dropdown_anim_08.png'
        }, {
            frame: 'widget://image/xiala/dropdown_anim_09.png'
        }, {
            frame: 'widget://image/xiala/dropdown_anim_10.png'
        }, {
            frame: 'widget://image/xiala/dropdown_loading_00.png'
        }, {
            frame: 'widget://image/xiala/dropdown_loading_01.png'
        }, {
            frame: 'widget://image/xiala/dropdown_loading_02.png'
        }]
    });
};

// 下拉刷新
function _downRefresh(callback, color) {
    if (color == null || color == '')
        color = '#6683ff';
    api.parseTapmode();
    api.setCustomRefreshHeaderInfo({
        bgColor: color, //（可选项）字符串类型；下拉刷新的背景颜色设置，支持 rgb、rgba、#，该背景大小同当前 window 或 frame 的宽高；默认：#C0C0C0
        textColor: '#fff', //文本颜色
        // images: ['../image/loading.gif'], //（可选项）数组类型；组成下拉过程和下拉加载状态的动画关键帧图片数组，这组图片随下拉高度自动播放关键帧图片：每下拉一定距离（阈值/图片数量），播放一帧关键帧图片；当下拉距离超过阈值时，播放速度加快，且循环播放；建议开发者传宽高不超过 200*60 的图片，否则图片将显示不全；若不传则使用默认图标；
        tips: { //（可选项）JSON 对象；整个下拉及加载过程的文字提示；不传则不显示文字区域
            pull: '下拉刷新', //（可选项）字符串类型；下拉过程（下拉高度未达到阈值前）的文字提示；不传则不显示该时段的文字提示
            threshold: '松开立即刷新', //（可选项）字符串类型；下拉过程（下拉高度达到或超过阈值）的文字提示；不传则不显示该时段的文字提示
            load: '正在刷新' //（可选项）字符串类型；加载状态的文字提示；不传则不显示该时段的文字提示
        }
    }, function() {
        callback();
    })
};

//返回按钮
function comeBack() {
    api.historyBack({  }, function(ret, err) {
        if (!ret.status) {
            var lastColor = document.querySelector('#header').getAttribute("last-color");
            api.setStatusBarStyle({
                style: lastColor ? lastColor : "dark"
            });
            api.closeWin();
        }
    });
};

function initHeard() {
    var headerNode = document.querySelector('#header');
    var heardColor = api.pageParam.heardColor;
    if (heardColor) {
        headerNode.setAttribute("last-color", heardColor);
    }
    var color = headerNode.getAttribute("data-color");
    if (color) {
        sysTop(color);
    } else {
        sysTop();
    }
    api.addEventListener({
        name: 'keyback'
    }, function(ret, err) {
        comeBack();
    });
};

//设置手机顶部状态样式
function sysTop(color) {
    if (!color) {
        var color = "dark";
    }
    var header = document.querySelector('#header');
    $api.fixStatusBar(header);
    api.setStatusBarStyle({
        style: color
    });
};
